package com.qf.ability.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qf.ability.auth.service.AuthService;
import com.qf.business.user.feign.UserFeign;
import com.qf.commons.core.utils.JwtUtils;
import com.qf.data.auth.vo.input.WxAuthUserInput;
import com.qf.data.user.entity.User;
import com.qf.data.user.vo.input.WxUserInput;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * description:
 * author: Ken
 * 公众号：Java架构栈
 */
@Service
@Slf4j
public class WxAuthServiceImpl implements AuthService {

    /**
     * Spring提供的用于发送Http请求的模块对象
     */
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private UserFeign userFeign;

    @Override
    public String wxlogin(WxAuthUserInput userInput) {
        //http请求，请求微信服务器获取用户的凭证（open_id/session_key）
//        Map<String, String> params = new HashMap<>();
//        params.put("appid", "wxdd8409202137787f");
//        params.put("secret", "27147d02f7cec9fc3de47a15f66e1b34");
//        params.put("js_code", userInput.getCode());
//        params.put("grant_type", "authorization_code");

        //使用restTemplate发送get请求
        String result = restTemplate.getForObject("https://api.weixin.qq.com/sns/jscode2session?appid=wxdd8409202137787f&secret=27147d02f7cec9fc3de47a15f66e1b34&js_code=" + userInput.getCode() + "&grant_type=authorization_code",
                String.class);
        log.info("[wxlogin] - 获取到微信登录的用户凭证 - {}", result);

        //转换成json对象
        JSONObject jsonObject = JSON.parseObject(result);
        String sessionKey = jsonObject.getString("session_key");
        String openId = jsonObject.getString("openid");

        WxUserInput wxInput = new WxUserInput();
        wxInput.setOpenId(openId);
        wxInput.setSessionKey(sessionKey);
        wxInput.setHeader(userInput.getHeader());
        wxInput.setNickName(userInput.getNickname());

        //调用用户微服务，将当前的数据同步到数据库中
        User user = userFeign.wxUserQuery(wxInput).result();

        //根据登录的用户信息，生成一个jwt的令牌，将令牌返回给客户端保存
        String jwtToken = JwtUtils.createJwtToken(user.getId());
        return jwtToken;
    }
}
